package com.example.mqttledmenu;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText username;
    private EditText password;
    private CheckBox isRemember;
    private TextView isForget;
    private Button login;
    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        login = findViewById(R.id.login);
        isRemember = findViewById(R.id.isRemember);
        isForget = findViewById(R.id.isForget);
        login.setOnClickListener(this);
        isRemember.setOnClickListener(this);
        isForget.setOnClickListener(this);

        //检测密码信息
        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        Boolean autoLogin = sp.getBoolean("remember", false);
        if (autoLogin) {
            username.setText(sp.getString("username", ""));
            password.setText(sp.getString("password", ""));
            isRemember.setChecked(true);
        } else {
            isRemember.setChecked(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                String usernameStr = username.getText().toString();
                String passwordStr = password.getText().toString();
                if (usernameStr.equals("") || passwordStr.equals("")) {
                    Toast.makeText(this, "用户名和密码不能为空！", Toast.LENGTH_SHORT).show();
                } else {
                    Retrofit retrofit = new Retrofit.Builder().baseUrl(Config.serverUrl).build();
                    UploadService uploadService = retrofit.create(UploadService.class);
                    Call<ResponseBody> call = uploadService.login(usernameStr, passwordStr);
                    call.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            String result = null;
                            try {
                                result = response.body().string();
                                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                                if (!returnData.get("code").toString().equals("200")) {
                                    Toast.makeText(LoginActivity.this, "用户名或密码错误~", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                JsonObject temp = new JsonParser().parse(returnData.get("data").toString()).getAsJsonObject();
                                Config.getInstance().setUserId(temp.get("userId").toString());//存储用户的id
                                Config.getInstance().setDepartmentTag(temp.get("tag").toString());//存储用户的负责专栏标识
                                Config.getInstance().setUserAvatar(temp.get("userAvatar").toString());//存储用户的头像
                                Config.getInstance().setDepartmentName("校园新闻");//存储用户的负责专栏名称
                                if (isRemember.isChecked()) {
                                    //存储用户用户名和密码
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("username", usernameStr);
                                    edit.putString("password", passwordStr);
                                    edit.putBoolean("remember", true);
                                    edit.apply();
                                }

                                Intent intent = new Intent();
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.setClass(getApplicationContext(), MainActivity.class);
                                startActivity(intent);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                }
                break;
            case R.id.isForget:
                Toast.makeText(this, "请联系辅导员重置密码哦！", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}